﻿using System;
using System.Collections.Generic;
using Autofac;
using JetBrains.Annotations;

namespace uMVP
{
    /// <summary>
    /// mvp管理器
    /// </summary>
    public interface IMvpManager
    {
        /// <summary>
        /// 打开View并执行View的Open函数
        /// </summary>
        /// <param name="viewName"></param>
        /// <returns></returns>
        IView Open(string viewName);
        
        /// <summary>
        /// 获得View的实例
        /// </summary>
        /// <param name="viewName"></param>
        /// <returns></returns>
        IView GetView(string viewName);
    }
    
    public class MvpManager : IMvpManager
    {
        private readonly ILifetimeScope _scope;

        public MvpManager([NotNull] ILifetimeScope scope)
        {
            _scope = scope ?? throw new ArgumentNullException(nameof(scope));
        }

        /// <summary>
        /// 打开指定的View的界面
        /// </summary>
        /// <param name="viewName">View的名字</param>
        /// <returns>返回View的实例</returns>
        public IView Open([NotNull] string viewName)
        {
            var view = GetView(viewName);
            view.OpenAsync();
            return view;
        }

        public IView GetView(string viewName)
        {
            if (string.IsNullOrEmpty(viewName))
                throw new ArgumentException("Value cannot be null or empty.", nameof(viewName));

            if (_scope.TryResolveNamed(viewName, typeof(IView), out object view))
            {
                return (IView)view;
            }

            throw new KeyNotFoundException($"viewName：{viewName} 没找到");
        }
    }
}